/**
 * SessionTabBar - Second-level Session Tab Navigation
 * 
 * Features:
 * - Display sessions for current assistant
 * - Switch between sessions
 * - Create new session
 * - Close session tabs
 * - Show unread counts
 * - Drag to reorder
 * - Right-click context menu
 */

import { useState, useRef } from 'react';
import { MessageSquare } from 'lucide-react';
import { Tab } from './Tab';
import { TabList } from './TabList';
import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuSeparator,
  ContextMenuTrigger,
} from '@/components/ui/context-menu';
import type { Session } from '@/store/session';

export interface SessionTabBarProps {
  sessions: Session[];
  activeId: string | null;
  assistantId: string | null;
  onSelect: (id: string) => void;
  onCreate: () => void;
  onClose?: (id: string) => void;
  onRename?: (id: string, title: string) => void;
  onDuplicate?: (id: string) => void;
  maxTabs?: number;
}

export function SessionTabBar({
  sessions,
  activeId,
  assistantId,
  onSelect,
  onCreate,
  onClose,
  onRename,
  onDuplicate,
  maxTabs = 20,
}: SessionTabBarProps) {
  const [draggedId, setDraggedId] = useState<string | null>(null);
  const [contextMenuSession, setContextMenuSession] = useState<Session | null>(null);

  // Filter sessions by current assistant
  const filteredSessions = sessions.filter(
    session => !assistantId || session.subAgentId === assistantId
  );

  const handleDragStart = (id: string) => (e: React.DragEvent) => {
    setDraggedId(id);
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', id);
  };

  const handleDragEnd = () => {
    setDraggedId(null);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  };

  const handleDrop = (targetId: string) => (e: React.DragEvent) => {
    e.preventDefault();
    const sourceId = e.dataTransfer.getData('text/plain');
    
    if (sourceId !== targetId) {
      // TODO: Implement reorder logic in store
      console.log(`Reorder session ${sourceId} to ${targetId}`);
    }
    
    setDraggedId(null);
  };

  const handleClose = (id: string) => (e: React.MouseEvent) => {
    e.stopPropagation();
    onClose?.(id);
  };

  const handleMiddleClick = (id: string) => () => {
    onClose?.(id);
  };

  const handleRename = () => {
    if (!contextMenuSession) return;
    
    const newTitle = prompt('重命名会话', contextMenuSession.title);
    if (newTitle && newTitle !== contextMenuSession.title) {
      onRename?.(contextMenuSession.id, newTitle);
    }
  };

  const handleDuplicate = () => {
    if (!contextMenuSession) return;
    onDuplicate?.(contextMenuSession.id);
  };

  const handleCloseOthers = () => {
    if (!contextMenuSession) return;
    
    filteredSessions.forEach(session => {
      if (session.id !== contextMenuSession.id) {
        onClose?.(session.id);
      }
    });
  };

  const handleCloseAll = () => {
    if (confirm('确定要关闭所有会话吗？')) {
      filteredSessions.forEach(session => onClose?.(session.id));
    }
  };

  if (filteredSessions.length === 0) {
    return null;
  }

  return (
    <div className="border-b bg-muted/30">
      <TabList
        onAdd={onCreate}
        showAddButton
        maxTabs={maxTabs}
      >
        {filteredSessions.map((session) => {
          const isActive = activeId === session.id;
          const messageCount = session.messages?.length || 0;
          
          return (
            <ContextMenu key={session.id}>
              <ContextMenuTrigger onContextMenu={() => setContextMenuSession(session)}>
                <Tab
                  id={session.id}
                  label={session.title || '未命名会话'}
                  icon={<MessageSquare className="w-4 h-4" />}
                  active={isActive}
                  closable
                  unreadCount={undefined} // TODO: Implement unread count
                  onClick={() => onSelect(session.id)}
                  onClose={handleClose(session.id)}
                  onMiddleClick={handleMiddleClick(session.id)}
                  draggable
                  onDragStart={handleDragStart(session.id)}
                  onDragEnd={handleDragEnd}
                  onDragOver={handleDragOver}
                  onDrop={handleDrop(session.id)}
                  className={cn(
                    'session-tab',
                    draggedId === session.id && 'opacity-50 scale-95'
                  )}
                />
              </ContextMenuTrigger>

              <ContextMenuContent>
                <ContextMenuItem onClick={handleRename}>
                  重命名
                </ContextMenuItem>
                <ContextMenuItem onClick={handleDuplicate}>
                  复制会话
                </ContextMenuItem>
                <ContextMenuSeparator />
                <ContextMenuItem 
                  onClick={() => onClose?.(session.id)}
                  className="text-destructive"
                >
                  关闭
                </ContextMenuItem>
                <ContextMenuItem onClick={handleCloseOthers}>
                  关闭其他
                </ContextMenuItem>
                <ContextMenuItem onClick={handleCloseAll}>
                  关闭全部
                </ContextMenuItem>
              </ContextMenuContent>
            </ContextMenu>
          );
        })}
      </TabList>
    </div>
  );
}

function cn(...classes: (string | boolean | undefined)[]) {
  return classes.filter(Boolean).join(' ');
}

